package logic

import (
	"common"
	"common/zapx"
	"errors"
	"gateway/internal/pb"
	"gateway/internal/types/v1/user"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"time"
)

type UserLogic struct {
	BaseLogicAbs
}

// NewUserLogic 创建用户逻辑对象
func NewUserLogic() *UserLogic {
	return &UserLogic{
		BaseLogicAbs: BaseLogicAbs{
			message: "",
		},
	}
}

// Register 注册用户
func Register(email, code, password string) error {
	//先验证验证码是否正确
	if err := CheckEmailVerifyCode(email, code, "register"); err != nil {
		return err
	}
	//验证通过,开始注册用户
	conn, err := grpc.Dial(
		common.ConsulSerUrl("user"),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	)
	defer conn.Close()
	if err != nil {
		return err
	}
	client := pb.NewUserClient(conn)
	ctx, cancel := common.WithTimeoutContext(time.Second * 2)
	defer cancel()
	_, err = client.Register(ctx, &pb.UserRegisterRequest{
		Email:    email,
		Password: password,
		NickName: email,
		Avatar:   nil,
	})
	if err != nil {
		return err
	}
	//把验证码设置为已使用
	if err := UseVerifyCode(email, code, "register"); err != nil {
		return err
	}
	return nil
}

// Profile 获取用户信息
func Profile(userId int32) *pb.UserProfileResponse {
	conn, err := grpc.Dial(
		common.ConsulSerUrl("user"),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	)
	if err != nil {
		zapx.Logger.Error("连接用户服务失败", zap.Error(err))
		return nil
	}
	defer conn.Close()
	userClient := pb.NewUserClient(conn)
	tctx, cancel := common.WithTimeoutContext(time.Second * 2)
	defer cancel()
	res, err := userClient.Profile(tctx, &pb.UserProfileRequest{
		UserId: userId,
	})
	if err != nil {
		zapx.Logger.Error("grpc查询用户失败", zap.Error(err))
		return nil
	}
	return res
}

// EditProfile 修改用户信息
func EditProfile(userId int32, req *user.EditProfileRequest) error {
	//图片是否存在
	if req.Avatar != nil {
		if !CheckMinioObjNameExists(*req.Avatar) {
			return errors.New("头像文件不存在")
		}
	}
	conn, err := grpc.Dial(
		common.ConsulSerUrl("user"),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	)
	if err != nil {
		zapx.Logger.Error("[EditProfile]连接user服务失败", zap.Error(err))
		return errors.New("系统错误")
	}
	defer conn.Close()
	userClient := pb.NewUserClient(conn)
	ctx, cancel := common.WithTimeoutContext(time.Second * 2)
	defer cancel()
	_, err = userClient.EditProfile(ctx, &pb.EditProfileRequest{
		UserId:   userId,
		NickName: req.NickName,
		Avatar:   req.Avatar,
	})
	return err
}
